<?php
namespace app\pay\controller\juyin;

class Daifu extends Base
{
    // 代付下单入口 
    public function index() {
        $data = input('post.');     // 获取客户端POST过来的参数
        // 验证签名
        $res = $this->verifySign($data, true);
        if($res) {
            $this->Request();
            // 组装POST到聚银的数据
            $postToJuyin = array(
                'memberid'    => $this->cfg->C('merchantId', false), // 更改商户号为聚银商户号
                'account'     => $data['account'],
                'bankName'    => $data['bankName'], 
                'bankCard'    => $data['bankCard'],
                'ownerName'   => $data['ownerName'],
                'provinceCode'=> $data['provinceCode'],
                'cityCode'    => $data['cityCode'],
                'amount'      => $data['amount'],
                'password'    => $this->cfg->C('daifuPwd', false), // 提现(代付)密码
                'mem_order'   => $data['mem_order'],
            );
             /*
             * 1.将订单信息保存到数据库中
             * 2.验证聚银签名并向聚银官方接口发起POST请求
             */
            $ret = $this->requestData($postToJuyin, 'daifu', true);
            // 接收聚银返回的数据并组装
            $result = $this->responseData($data['memberid'], $ret);
            $retData = json_decode($ret, true);
            if($retData['code'] == '11') {
                // 将代付结算记录保存到数据库中
                $this->daifuOrderAdd($data);
            }
            return $result;
        } else {
            return $res;
        }
    }
    
    // 接收聚银返回的数据并组装
    public function responseData($merchantId, $data) {
        $retData = json_decode($data, true);
        if($retData['code'] == '11') {
            // 数据组装
            $result = array(
                'code'      => $retData['code'],
                'order'     => $retData['order'],
                'account'   => $retData['account'],
                'memberno'  => $merchantId,
                'amount'    => $retData['amount'],
                'msg'       => $retData['msg'],
            );
            // 生成新的签名
            $newJuyinSignVal = $this->payRequest->createJuyinSign($result, true);
            $result['signature'] = $newJuyinSignVal;
        } else {
            $result = array(
                'code' => $retData['code'],
                'msg'  => $retData['msg']
            );
        }
        return json_encode($result, true);
    }
    
    // 将代付结算记录添加
    public function daifuOrderAdd($data) {
        $orderInfo = array(
            'mem_order'     => $data['mem_order'],
            'memberid'      => $data['memberid'],
            'time'          => time(),
            'account'       => $data['account'],
            'bank_code'     => $data['bankName'],
            'bank_card'     => $data['bankCard'],
            'owner_name'    => $data['ownerName'],
            'amount'        => $data['amount'],
            'status'        => 0,
            'remark'        => null,
        );
        model('PayDaifuOrder')->add($orderInfo);
    }
}

